package com.onlinevideo.filter;


import com.onlinevideo.util.EncodingWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 编码过滤器，将所有的请求和响应设置为UTF-8
 */
public class EncodingFilter implements Filter {
    public static String encoding = "UTF-8";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if ("GET".equalsIgnoreCase(request.getMethod())) {
            EncodingWrapper wrapper = new EncodingWrapper(request, "UTF-8");
            filterChain.doFilter(wrapper, response);
        } else {
            request.setCharacterEncoding(encoding);
            response.setContentType("text/html;charset=" + encoding);
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }


}
